package com.sh.data.engine.common.util;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.*;

/**
 * @author boyue.wjl
 */
public class NumberUtil {
    public static Integer parseInt(String intStr) {
        if (StringUtils.isBlank(intStr)) {
            return null;
        }
        try {
            return Integer.parseInt(intStr);
        } catch (Exception e) {
            return null;
        }
    }

    public static Long parseLong(String intStr) {
        if (StringUtils.isBlank(intStr)) {
            return null;
        }
        try {
            return Long.parseLong(intStr);
        } catch (Exception e) {
            return null;
        }
    }

    public static List<Long> getLongIds(List<String> strList) {
        if (CollectionUtils.isEmpty(strList)) {
            return Collections.emptyList();
        }
        Set<Long> ids = new TreeSet<>();
        for (String str : strList) {
            if (StringUtils.isBlank(str)) {
                continue;
            }
            String[] idsArr = str.split(",");
            for (String temp : idsArr) {
                if (StringUtils.isBlank(temp)) {
                    continue;
                }
                Long id = parseLong(temp);
                if (id != null) {
                    ids.add(id);
                }
            }
        }
        return new ArrayList<>(ids);
    }

    public static String sizeFormatNum2String(Long size) {

        if (size == null) {
            return "0.00KB";
        }

        boolean flag = false;
        if (size.longValue() < 0) {
            size = 0 - size;
            flag = true;
        }
        String s;
        if (size.longValue() > 1024L * 1024L * 1024L) {
            s = String.format("%.2f", (double) size.longValue() / (1024L * 1024L * 1024L)) + "GB";
        } else if (size.longValue() > 1024L * 1024L) {
            s = String.format("%.2f", (double) size.longValue() / 1048576) + "MB";
        } else if (size.longValue() > 1024) {
            s = String.format("%.2f", (double) size.longValue() / 1024) + "KB";
        } else {
            s = String.format("%.2f", (double) size.longValue()) + "B";
        }

        if (flag && StringUtils.isNotBlank(s)) {
            s = "-" + s;
        }
        return s;
    }
}
